package com.apes.hr.cultivate.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.cultivate.model.*;
import com.apes.hr.cultivate.model.CultivatePlan;
import com.apes.hr.cultivate.repository.*;
import com.apes.hr.cultivate.repository.CultivatePlanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能：培训计划
 *
 * @author Linwz
 * @create 2019-06-17 15:11
 */
@Service("hrCultivatePlanService")
public class CultivatePlanService extends DomainService {
    @Autowired
    public CultivatePlanRepository cultivatePlanRepository;
    @Autowired
    public CultivatePlanItemRepository cultivatePlanItemRepository;
    @Autowired
    public CourseRepository courseRepository;
    @Autowired
    public CultivatePlanArrangeRepository arrangeRepository;

    /**
     * 添加中间表信息
     * @param
     */
//    private void setCourseList(SimpleRequest request){
//        JSONArray cultivatePlanItems = request.get("");
//        cultivatePlanItems.forEach(cultivatePlanItem -> {
//            // 添加中间表信息
//            List<JSONObject> courseList = cultivatePlanItem.getCourseList();
//            if (courseList != null) {
//                List<Course> courses = new ArrayList<>();
//                courseList.stream().forEach(
//                        (postJ) -> {
//                            Course course = courseRepository.findOne(postJ.getString("id"));
//                            courses.add(course);
//                        }
//                );
//                cultivatePlanItem.setCourses(courses);
//            }
//        });
//    }

    /**
     * 检查传入的 时间段
     * @param cultivatePlan
     */
    private void checkTimes( CultivatePlan cultivatePlan ){
        Set<CultivatePlanItem> itemSet =  cultivatePlan.getCultivatePlanItems();
        itemSet.forEach(item ->{
           Set<CultivatePlanTime> timeSet = item.getcultivatePlanTimes();
            Set<CultivatePlanTime> newTimeList = new HashSet<>();
            timeSet.forEach(time ->{
              if (time.getCourseDate()!=null || time.getCourseStateTime()!=null || time.getCourseEndTime()!= null ){
                  newTimeList.add(time);
              }
           });
            newTimeList.forEach(time ->{
                if(time.getCourseDate()==null || time.getCourseStateTime()==null || time.getCourseEndTime()==null)throw new RuntimeException("请检查开课时间段,时间段字段不予许为空!");
//                time.setCourseStateTime(Timestamp.valueOf(time.getCourseStateTime().toString()));
//                time.setCourseEndTime(Timestamp.valueOf(time.getCourseEndTime().toString()));
            });
            timeSet = newTimeList;
            item.setcultivatePlanTimes(timeSet);
       });



    }
    /**
     * 功能：创建
     * @param request
     * @return
     */
    public CultivatePlan save(SimpleRequest request) {
        CultivatePlan cultivatePlan = request.getO(CultivatePlan.class);
        checkTimes(cultivatePlan);
        cultivatePlan.setState("create");  //设置当前的状态
//        setCourseList(request);
        String name = request.get("name");
        CultivatePlan cultivatePlanName = cultivatePlanRepository.find(name);
        if (cultivatePlanName!=null)throw new RuntimeException("该名称已被使用,请修改!");
        return cultivatePlanRepository.saveAndFlush(cultivatePlan);
    }


    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public CultivatePlan update(SimpleRequest request) {
        checkData(request);
        CultivatePlan cultivatePlan = request.getO(CultivatePlan.class);
        checkTimes(cultivatePlan);
//        setCourseList(request);
        return cultivatePlanRepository.saveAndFlush(cultivatePlan);

    }


    /**
     * 功能：审核培训计划
     *
     * @param request
     * @return
     */
    public CultivatePlan approve(SimpleRequest request) {
        CultivatePlan oldBill = checkData(request);
        if (oldBill.getApproveDate() != null) throw new RuntimeException("培训计划：" + request.get("id") + " 在系统中已审核。");
        CultivatePlan ptType = request.getO(CultivatePlan.class);
        ptType.setState("approve");
        ptType.setApproveDate(new Date());
        ptType.setApproveUid(this.getPerson(request));
        checkTimes(ptType);
        return cultivatePlanRepository.saveAndFlush(ptType);
    }

    /**
     * 检查数据判断，判读当前的输入版本信息
     * @param request
     */
    public CultivatePlan checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");
        String name = request.get("name");
        CultivatePlan cultivatePlanName = cultivatePlanRepository.find(name);
        if (cultivatePlanName!=null && !cultivatePlanName.getId().equals(id))throw new RuntimeException("该名称已被使用,请修改!");
        // 从数据库中取数，检查数据
        CultivatePlan cultivatePlan = cultivatePlanRepository.findOne(id);
        if (cultivatePlan == null) throw new RuntimeException("培训计划【" + id + "】在系统中不存在。");
        if (cultivatePlan.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return cultivatePlan;
    }

    /***
     * 功能： 删除
     * @param request
     * @return
     * @throws RuntimeException
     */
    public String delete(SimpleRequest request) throws RuntimeException {
        checkData(request);
        // 设置删除人以及状态
        CultivatePlan requestCultivatePlan = request.getO(CultivatePlan.class);

        requestCultivatePlan.setDeleteId(this.getPerson(request)); //设置人员
        requestCultivatePlan.setDeleteDate(new Date()); // 设置时间
        requestCultivatePlan.setState("delete");  //设置当前的状态为删除
        cultivatePlanRepository.saveAndFlush(requestCultivatePlan);

        return "删除成功！";
    }


    /**
     * 功能：终止培训计划
     *
     * @param request
     * @return
     */
    public CultivatePlan repeal(SimpleRequest request) {
        CultivatePlan cultivatePlan = request.getO(CultivatePlan.class);
        List<CultivatePlanArrange> arrangeList = arrangeRepository.findByCultivatePlan(cultivatePlan);
        cultivatePlan.getCultivatePlanItems().forEach(cultivatePlanItem -> {
            if(cultivatePlanItem.isRepeal()){
                arrangeList.forEach(arrange ->{
                    if( arrange.getcourseSet().contains(cultivatePlanItem.getCourse()))throw new RuntimeException("明细已被使用!不可终止!");
                });

            }
        });
        return cultivatePlanRepository.saveAndFlush(cultivatePlan);
    }

    /***
     * 功能：回车查询
     * @param request
     * @return
     */
    public CultivatePlan findOne(SimpleRequest request) {
        CultivatePlan CultivatePlan = cultivatePlanRepository.findOne((String) request.get("id"));
        return CultivatePlan;
    }


    /***
     * 功能：查询 已审核且 在有效期内
     * @param request
     * @return
     */
    public Page<CultivatePlan> findByStateAndBeginDateAndEndDate(SimpleRequest request) {
        return cultivatePlanRepository.findByStateAndBeginDateAndEndDate((String) request.get("key"),PageRequest.of(request.get("page"), request.get("size")));
    }


    /***
     * 功能：查询 已审核
     * @param request
     * @return
     */
    public Page<CultivatePlan> findByState(SimpleRequest request) {
        return cultivatePlanRepository.findByState((String) request.get("key"),PageRequest.of(request.get("page"), request.get("size")));
    }
}
